<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>健康管理系统</h2>
        <p>用户注册</p>
      </div>
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
      >
        <el-form-item prop="studentNumber">
          <el-input v-model="registerForm.studentNumber" placeholder="请输入学号/工号">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="verifyCode">
          <div class="verify-code-container">
            <el-input v-model="registerForm.verifyCode" placeholder="请输入验证码" />
            <el-button
              type="primary"
              class="get-code-btn"
              :disabled="codeBtnDisabled"
              @click="sendVerifyCode"
            >
              {{ codeButtonText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            placeholder="请输入密码"
            type="password"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            placeholder="请确认密码"
            type="password"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-select v-model="registerForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="管理员"></el-option>
            <el-option label="教师" value="教师"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary">用户协议</el-link>
            和
            <el-link type="primary">隐私政策</el-link>
          </el-checkbox>
        </el-form-item>
        <el-button
          type="primary"
          class="register-button"
          @click="handleRegister"
          :loading="loading"
        >
          注册
        </el-button>
        <div class="login-link">
          <span>已有账号?</span>
          <router-link to="/login">返回登录</router-link>
        </div>
      </el-form>
    </div>
    <div class="project-info">西南科技大学智慧教育研究中心项目及项目编号</div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone } from '@element-plus/icons-vue'
import { user } from '@/api'
import type { FormInstance, FormItemRule } from 'element-plus'

const router = useRouter()
const registerFormRef = ref<FormInstance | null>(null)
const loading = ref(false)
const countdown = ref(0)
const timer = ref<number | null>(null)

const registerForm = reactive({
  studentNumber: '',
  username: '',
  phone: '',
  email: '',
  verifyCode: '',
  password: '',
  confirmPassword: '',
  role: '',
  agreement: false,
})

// 发送验证码倒计时按钮文字
const codeButtonText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}秒后重试` : '获取验证码'
})

// 验证码按钮是否禁用
const codeBtnDisabled = computed(() => {
  return countdown.value > 0 || !registerForm.email
})

// 自定义校验规则
const validatePass = (rule: FormItemRule, value: string, callback: (error?: Error) => void) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule: FormItemRule, value: string, callback: (error?: Error) => void) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validateEmail = (rule: FormItemRule, value: string, callback: (error?: Error) => void) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (value === '') {
    callback(new Error('请输入邮箱地址'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}

const validateStudentNumber = (
  rule: FormItemRule,
  value: string,
  callback: (error?: Error) => void,
) => {
  if (value === '') {
    callback(new Error('请输入学号/工号'))
  } else {
    callback()
  }
}

const validatePhone = (rule: FormItemRule, value: string, callback: (error?: Error) => void) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validateAgreement = (
  rule: FormItemRule,
  value: boolean,
  callback: (error?: Error) => void,
) => {
  if (!value) {
    callback(new Error('请阅读并同意用户协议和隐私政策'))
  } else {
    callback()
  }
}

const registerRules = {
  studentNumber: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' },
    { validator: validateStudentNumber, trigger: 'blur' },
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: ['blur', 'change'] },
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePass2, trigger: ['blur', 'change'] },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  agreement: [{ validator: validateAgreement, trigger: 'change' }],
}

// 发送验证码
const sendVerifyCode = async () => {
  // 先验证邮箱字段
  try {
    await registerFormRef.value?.validateField('email')

    // 开始倒计时
    countdown.value = 60
    // 调用验证码发送API
    const res = await user.sendCaptcha(registerForm.email)

    if (res.code === 200) {
      ElMessage.success(`验证码已发送至邮箱: ${registerForm.email}`)
    } else {
      ElMessage.error(res.message || '验证码发送失败')
      countdown.value = 0
      return
    }

    // 启动定时器
    timer.value = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0 && timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
    }, 1000)
  } catch (error) {
    console.error('邮箱验证失败', error)
  }
}

const handleRegister = async () => {
  try {
    await registerFormRef.value?.validate()

    loading.value = true
    // 构造注册请求数据
    const registerData = {
      username: registerForm.username,
      email: registerForm.email,
      captcha: registerForm.verifyCode,
      password: registerForm.password,
      checkPassword: registerForm.confirmPassword,
      phone: registerForm.phone,
      role: registerForm.role,
      studentNumber: registerForm.studentNumber,
    }

    // 调用注册API
    const res = await user.register(registerData)

    if (res.code === 200) {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(res.message || '注册失败')
    }
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  background-image: linear-gradient(to right, #f5f7fa, #c3cfe2);
  flex-direction: column;
}

.register-box {
  width: 400px;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h2 {
  font-size: 24px;
  color: #409eff;
  margin-bottom: 10px;
}

.register-header p {
  color: #606266;
  font-size: 16px;
}

.register-form {
  margin-bottom: 20px;
}

.register-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  margin-top: 10px;
}

.login-link {
  margin-top: 20px;
  text-align: center;
  color: #606266;
}

.login-link a {
  margin-left: 5px;
  color: #409eff;
  text-decoration: none;
}

.verify-code-container {
  display: flex;
  align-items: center;
}

.verify-code-container .el-input {
  flex: 1;
}

.get-code-btn {
  margin-left: 10px;
  white-space: nowrap;
  min-width: 100px;
}

@media screen and (max-width: 480px) {
  .register-box {
    width: 90%;
    padding: 30px;
  }
}

.project-info {
  margin-top: 20px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}
</style>
